package com.bootdo.front.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.domain.CheckFileDO;
import com.bootdo.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 文件检测接口
 */
@Controller
@RequestMapping("/front/check/")
@Slf4j
public class FrontCheckController {

    //fileType fileName
    //101      待检测图片
    //102      待检测视频
    //103      待检测音频
    //201      支持图片

    //public static final String URL = "http://61.149.143.242:10001";
    public static final String URL = "http://127.0.0.1:10001";

    /**
     * 上传检测文件接口
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public R uploadFile(CheckFileDO checkFileDO, MultipartFile file) {
        String result = uploadFilePost(URL + "/uploadFile",checkFileDO.getId(),checkFileDO.getBizType(),checkFileDO.getFileType(),file);
        HashMap<String,Object> map = JSON.parseObject(result, HashMap.class);
        return R.ok(map);
    }

    public static String uploadFilePost(String url, String id,String bizType,String fileType, MultipartFile file){
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//解决返回中文乱码问题
        builder.setCharset(Charset.forName("UTF-8")); //此处踩坑，转发出去的filename依然为乱码
        ContentType strContent = ContentType.create("text/plain",Charset.forName("UTF-8"));
        builder.addTextBody("id", id,strContent);
        builder.addTextBody("bizType", bizType,strContent);
        builder.addTextBody("fileType", fileType,strContent);
        try {
            builder.addPart("file", new ByteArrayBody(file.getBytes(), file.getOriginalFilename()));
            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if(null != responseEntity) {
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

    /**
     * 获取文件信息
     * @param checkFileDO
     * @return
     */
    @PostMapping("/getFile")
    @ResponseBody
    public R getFile(CheckFileDO checkFileDO) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",checkFileDO.getId());
        map.put("fileID",checkFileDO.getFileID());
        String result = sendPost(URL + "/getFile",map);
        return R.ok().put("fileUrl",result);
    }

    /**
     * 文件检测接口
     * @param checkFileDO
     * @return
     */
    @PostMapping("/startDetect")
    @ResponseBody
    public R startDetect(CheckFileDO checkFileDO) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",checkFileDO.getId());
        String result = sendPost(URL + "/startDetect",map);
        HashMap<String,Object> map1 = JSON.parseObject(result, HashMap.class);
        return R.ok(map1);
    }

    /**
     * 获取文件检测信息接口
     * @param checkFileDO
     * @return
     */
    @PostMapping("/getRes")
    @ResponseBody
    public R getRes(CheckFileDO checkFileDO) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",checkFileDO.getId());
        map.put("bizType",checkFileDO.getBizType());
        String result = sendPost(URL + "/getRes",map);
        HashMap<String,Object> map1 = JSON.parseObject(result, HashMap.class);
        return R.ok(map1);
    }

    public static String sendPost(String url, Map<String, Object> map){
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//解决返回中文乱码问题
        builder.setCharset(Charset.forName("UTF-8")); //此处踩坑，转发出去的filename依然为乱码
        ContentType strContent = ContentType.create("text/plain",Charset.forName("UTF-8"));
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> en = it.next();
            String key = en.getKey();
            String value = (String) en.getValue();
            if (value != null) {
                builder.addTextBody(key, value,strContent);
            }
        }
        try {
            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if(null != responseEntity) {
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id","100000015");
        jsonObject.put("bizType","3102");
        String mdata = jsonObject.toString();
        doJsonPostFor(URL + "/getRes",mdata);
        //HttpRequestUtil.postJSON(URL + "/getRes",jsonObject);
    }

    public static String doJsonPostFor(String url, String mdata){
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//解决返回中文乱码问题
        builder.setCharset(Charset.forName("UTF-8")); //此处踩坑，转发出去的filename依然为乱码
        ContentType strContent = ContentType.create("text/plain",Charset.forName("UTF-8"));
        //builder.addTextBody("data", mdata,strContent);
        builder.addTextBody("id", "100000015",strContent);
        builder.addTextBody("bizType", "3102",strContent);
        try {
            //builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
            /*File file1 = new File(file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
            builder.addPart("image", new InputStreamBody(new FileInputStream(file1), file1.getName()));*/
            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if(null != responseEntity) {
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

}
